package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        String errMsg = e.getMessage();
        log.error(errMsg);

        //对异常信息进行处理
        if (errMsg.contains("Duplicate")) {
            String msg = errMsg.split(" ")[2];
            return R.error(msg + "重复了!");
        }

        return R.error("未知错误!");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> handlerCustomException(CustomException e) {
        String errMsg = e.getMessage();
        log.error(errMsg);
        return R.error(errMsg);
    }
}
